(function(mod) {
    if (typeof exports == "object" && typeof module == "object") // CommonJS
        module.exports = mod();
    else if (typeof define == "function" && define.amd) // AMD
        return define([], mod);
    else // Plain browser env
        this.BusinessSelector = mod();
})(function() {
    var model = '<div id="BusinessSelector" class="modal fade" tabindex="-1" role="dialog">' +
                    '<div class="modal-dialog" role="document">' +
                        '<div class="modal-content">' +
                            '<div class="modal-header">' +
                                '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
                                '<h4 class="modal-title"></h4>' +
                            '</div>' +
                            '<div class="modal-body">' +
                                '<div id="search-panel" class="panel panel-default">' +
                                    '<div class="panel-body">' +
                                        '<form class="form-inline">' +
                                            '<div class="form-group">' +
                                                '<input type="text" class="form-control" id="taskName" placeholder="业务名">' +
                                            '</div>' +
                                            '<button type="button" class="btn btn-default search">查询</button>' +
                                            '<button type="button" class="btn btn-danger clear-search">清除查询结果</button>' +
                                        '</form>' +
                                    '</div>' +
                                '</div>' +
                                '<div class="business-Panel">' +
                                    '<div class="row">' +
                                        '<div class="col-md-6">' +
                                            '<div class="panel">' +
                                                '<div class="panel-heading">' +
                                                    '<h3 class="panel-title">可选业务</h3>' +
                                                '</div>' +
                                                '<div class="panel-body">' +
                                                    '<ul id="tree" class="ztree" style="width:260px; overflow:auto;"></ul>' +
                                                    '<ul id="search-result">' +
                                                    '</ul>' +
                                                '</div>' +
                                            '</div>' +
                                        '</div>' +
                                        '<div class="col-md-6">' +
                                            '<div class="panel">' +
                                                '<div class="panel-heading">' +
                                                    '<h3 class="panel-title">已选业务</h3>' +
                                                '</div>' +
                                                '<div id="selected-panel" class="panel-body">' +
                                                    '<ul></ul>' +
                                                '</div>' +
                                            '</div>' +
                                        '</div>' +
                                    '</div>' +
                                '</div>' +
                            '</div>' +
                            '<div class="modal-footer">' +
                                '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>' +
                                '<button id="save" type="button" class="btn btn-primary">Save changes</button>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                '</div>';
    var defaults = {
        element : null,
        title : '业务选择',
        selector : [],
        setting : {
            async: {
                enable: true,   //设置启用异步加载
                type: "get",   //异步加载类型:post和get
                contentType: "text", //定义ajax提交参数的参数类型，一般为json格式
                autoParam:["id=id"],
                url: "/index.php?m=Admin&c=Business&a=selector",
            },
            check: {
                enable: false
            },
            callback : {
                onClick : $.noop(),
                onCheck : $.noop()
            }
        }
    };

    function BusinessSelector(options){
        var option = $.extend({},defaults,options);
        option.setting.callback.onClick = this._click.bind(this);
        if(option.multiple){
            option.setting.check.enable = true;
            option.setting.callback.onCheck = this._check.bind(this);
        }
        this._init(option);
    }

    BusinessSelector.prototype._init = function(option){
        this.modal = $(model);
        this.option = option;
        var _this = this;
        //bindElement(_this);

        $(option.element).on('click',function(){
            _this._show();
        });
    };
    BusinessSelector.prototype._click = function(event,treeId,treeNode){
        console.log(this);
        console.log(treeNode);
        this._change([treeNode]);
    };
    BusinessSelector.prototype._check = function(event,treeId,treeNode){
        var zTree = $.fn.zTree.getZTreeObj("tree");
        var checkNodes = zTree.getCheckedNodes(true);
        this._change(checkNodes);
    };

    BusinessSelector.prototype._show = function(){
        var _this = this;
        console.log('show');

        var t = _this.modal.find('#tree');
        $.fn.zTree.init(t, _this.option.setting);

        $(document.body).append(this.modal);
        _this.modal.modal('show');
        bindElement(_this);
        bindEvent(_this);
    };
    BusinessSelector.prototype._hide = function(){
        console.log('hide');
        this.modal.modal('hide');
        this.modal.remove();
    };
    BusinessSelector.prototype._change = function(nodes){
        console.log(nodes);
        var _this = this;
        if(!_this.option.multiple && this.modal.find('#selected-panel ul li').length >= 1){
            alert('不能选择多个');return;
        }
        var selected = this.modal.find('#selected-panel ul');
        var array = [];
        for(var i=0;i<nodes.length;i++){
            var exist = false;
            selected.find('li').each(function(){
                if(parseInt($(this).data('id')) === parseInt(nodes[i].id)){
                    exist = true;
                    return;
                }
            });
            if(!exist){
                var li = $('<li data-id="'+nodes[i].id+'" data-name="'+nodes[i].name+'"><i class="glyphicon glyphicon-user"></i><span>'+nodes[i].name+'</span><i class="glyphicon glyphicon-remove"></i></li>');
                array.push(nodes[i].id);
                selected.append(li);
            }
        }
    };

    /**
     * 绑定事件
     * @param _this
     */
    function bindEvent(_this) {
        _this.modal.on('hidden.bs.modal', function (e) {
            _this._hide();
        });
        _this.modal.on('click','i.glyphicon-remove',function(){
            remove(this);
        });
    }

    /**
     * 绑定界面元素
     * @param _this
     */
    function bindElement(_this){
        _this.modal.find('.modal-title').text(_this.option.title);
        _this.modal.find('.modal-footer').empty();
        _this.modal.find('#selected-panel ul').empty();
        _this.modal.find('#search-panel input[type=text]').val('');
        _this.modal.find('#search-panel button.clear-search').on('click',function(){
            _this.modal.find('#search-result').empty().hide();
            _this.modal.find('#tree').show();
        });
        _this.modal.find('#search-panel button.search').on('click',function(){
            var keyword = $(this).closest('form').find('input[type=text]').val();
            url = '/index.php?m=Admin&c=Business&a=search';
            _this.modal.find('#search-result').empty();
            search(keyword,url,function(data){
                _this.modal.find('#tree').hide();
                for(var i=0;i<data.length;i++){
                    console.log(data[i]);
                    var line = $('<li data-id="'+data[i].ID+'" data-name="'+data[i].Name+'"><span class="icon"></span>'+data[i].Name+'</li>');
                    _this.modal.find('#search-result').append(line);
                }
                _this.modal.find('#search-result').on('click','li',function(){
                    var obj = {
                        id : $(this).data('id'),
                        name : $(this).data('name')
                    };
                    _this._change([obj]);
                });
                _this.modal.find('#search-result').show();
            });
        });

        var buttonList = _this.option.button;
        for(var i = 0;i < buttonList.length;i++){
            if(buttonList[i].onclick === 'close'){
                var button = $('<button type="button" class="btn btn-default" data-dismiss="modal">'+buttonList[i].title+'</button>');
                _this.modal.find('.modal-footer').append(button);
            }else{
                var currentButton = buttonList[i];
                var button = $('<button type="button" class="btn btn-primary">'+buttonList[i].title+'</button>');
                _this.modal.find('.modal-footer').append(button);
                button.on('click',function(){
                    var param = [];
                    _this.modal.find('#selected-panel ul').find('li').each(function(){
                        var line = {id:$(this).data('id'),name:$(this).data('name')};
                        param.push(line);
                    });
                    if(!_this.option.multiple && param.length > 1){
                        console.log(_this.option.multiple);
                        alert('不能选择多个');return;
                    }
                    if(param.length > 0){
                        if(param.length < 2){
                            param = param[0];
                        }
                    }
                    _this.modal.modal('hide');
                   currentButton.onclick(param);
                });
            }
        }
    }

    function remove(element){
        $(element).closest('li').remove();
    }
    function search(keyword,url,callback){
        $.ajax(url,{
            type : 'get',
            dataType : 'json',
            data : {keyword : keyword}
        }).done(function(data){
            callback && callback(data);
        });
    }

    return BusinessSelector;
});